package web.pre;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import entity.News;
import entity.Product;
import entity.ProductCategory;
import service.NewsService;
import service.ProductCategoryService;
import service.ProductService;

public class HomeServlet extends HttpServlet{
	
	public ProductCategoryService prcat=new ProductCategoryService();
	
	public ProductService  pro=new ProductService();
	
	public NewsService news=new NewsService();
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		//一个Servlet可以处理多个机试
		String action = request.getParameter("action");
		if(action!=null){
			switch (action) {
			case "index":
				index(request,response);
				break;
			default:
				break;
			}
		}else {
			response.sendRedirect("Regist.jsp");
		}
	}
	private void index(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		List<ProductCategory> listProductCategory =prcat.prcatList();
		
		Map<Integer,List<Product>> mapProductList=new HashMap<Integer, List<Product>>();
		
		int currPage=1;//第一页
		int pageSize=6;//页面大小
		
		for(ProductCategory productCategory : listProductCategory){
			if(productCategory.getType() == 1){
			     List<Product>	 listProduct=pro.proList(productCategory.getId(),1,currPage,pageSize);
			     mapProductList.put(productCategory.getId(), listProduct);
			}
		}
		
		List<News> NewsList = news.NewsList();
		
		request.setAttribute("NewsList", NewsList);
		
		request.getSession().setAttribute("mapProductList", mapProductList);
		
		request.setAttribute("listProductCategory", listProductCategory);
		
		//mapProductList[548]
		
		request.getRequestDispatcher("Index.jsp").forward(request, response);
	}
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doGet(request, response);
	}
}
